const { REQ_PATH, REF_PATH, API_HOST } = require('./config')
const axios = require('axios')
const router = require('koa-router')()
const cheerio = require('cheerio')
// 获取番剧的信息 或者 番剧的剧集信息
router.get('/info', async (ctx, next) => {
  const url = `${REF_PATH}/bangumi/play/${ctx.request.query.id}`
  const res = await axios.get(url, {
    headers: {
      referer: `${REF_PATH}/bangumi/play/${ctx.request.query.id}`,
      origin: REF_PATH
    }
  })
  res.data = res.data.replace('<script>window.__INITIAL_STATE', '<script id="configjs">window.__INITIAL_STATE')
  const $ = cheerio.load(res.data)
  let result = {}
  if ($('#configjs').length) {
    let configjs = $('#configjs').html()
    const position = configjs.indexOf('(function()')
    if (position > -1) {
      // 删除多余脚本
      configjs = configjs.substring(0, position - 1)
      configjs = configjs.replace('window.__INITIAL_STATE__=', '')
      const config = JSON.parse(configjs)
      result = { code: 0, data: config, message: '解析成功' }
    } else {
      // 解析失败
      result = { code: -1, data: null, message: '解析失败' }
    }
  } else {
    // 解析数据失败
    result = { code: -1, data: null, message: '解析失败' }
  }
  ctx.response.body = result
  await next()
})

// 获取番剧信息
router.get('/season', async (ctx, next) => {
  const url = `${API_HOST}/pgc/view/web/season`
  const res = await axios.get(url, {
    headers: {
      referer: `${REF_PATH}/bangumi/play/ss${ctx.request.query.ep_id}`,
      origin: REF_PATH
    },
    params: ctx.request.query
  })
  ctx.response.body = res.data
  await next()
})

// 获取播放地址
router.get('/playurl', async (ctx, next) => {
  const url = `${API_HOST}/pgc/player/web/playurl/html5`
  const res = await axios.get(url, {
    headers: {
      referer: `${REF_PATH}/bangumi/play/${ctx.request.query.ep_id}`,
      origin: REF_PATH
    },
    params: ctx.request.query
  })
  ctx.response.body = res.data
  await next()
})

// 获取相关视频
router.get('/related', async (ctx, next) => {
  const url = `${API_HOST}/pgc/web/recommend/related/recommend`
  const res = await axios.get(url, {
    headers: {
      referer: `${REF_PATH}/bangumi/play/${ctx.request.query.ep_id}`,
      origin: REF_PATH
    },
    params: ctx.request.query
  })
  ctx.response.body = res.data
  await next()
})

// 获取评论
router.get('/comment', async (ctx, next) => {
  const url = `${REQ_PATH}/v2/reply`
  const res = await axios.get(url, {
    headers: {
      referer: `${REF_PATH}/index.html`,
      origin: REF_PATH
    },
    params: ctx.request.query
  })
  ctx.response.body = res.data
  await next()
})

module.exports = router
